package com.example.treeHole.service.impl;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.example.treeHole.dao.UserInfoMapper;
import com.example.treeHole.dao.VirtualCharacterMapper;
import com.example.treeHole.exception.CustomException;
import com.example.treeHole.service.UserService;
import com.example.treeHole.utils.BaseContext;
import com.example.treeHole.utils.JwtTokenUtils;
import com.example.treeHole.utils.MD5;
import com.example.treeHole.utils.Uuid;
import com.example.treeHole.vo.UserInfo;
import com.example.treeHole.vo.VirtualCharacter;
import com.example.treeHole.vo.dto.UserInfoDto;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;


import java.util.*;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private VirtualCharacterMapper virtualCharacterMapper;

    @Override
    public List<UserInfo> getAll() {
        return userInfoMapper.findAll();
    }

    @Override
    public PageInfo<UserInfo> findBySearch(UserInfoDto userInfo) {
        PageHelper.startPage(userInfo.getPageNum(), userInfo.getPageSize());
        List<UserInfo> users = userInfoMapper.findBySearch(userInfo);
        return PageInfo.of(users);
    }


    @Override
    public Integer add(UserInfo userInfo) {
        int insert;
        if (StringUtils.isEmpty(userInfo.getUserName())) {
            return 0;
        }
        //新增用户
        if (StringUtils.isEmpty(userInfo.getUserId())) {
            //没有密码添加默认密码为 123456
            if (StringUtils.isEmpty(userInfo.getPassWord())) {
                userInfo.setPassWord(MD5.DefaultPassword());
            } else {
                //有密码进行md5加密
                userInfo.setPassWord(MD5.md5(userInfo.getPassWord()));
            }
            //没有上头像设置默认头像
            if(StringUtils.isEmpty(userInfo.getUserIcon())){
                if (userInfo.getUserSex() == "1"){
                    userInfo.setUserIcon("1709365202947");
                }else {
                    userInfo.setUserIcon("1709365417945");
                }
            }
            userInfo.setUserId(Uuid.getUuID());
            userInfo.setCreateBy(BaseContext.getCurrentId());
            userInfo.setCreateDate(new Date());
            userInfo.setLastUpdateDate(new Date());
            //添加的用户默认为普通用户
            userInfo.setRoleId("2C01305AF96C4556BCE7719AACC0DEC7");
            userInfo.setLastUpdateBy(BaseContext.getCurrentId());
            insert = userInfoMapper.insert(userInfo);
        } else {
            //更新用户
            userInfo.setLastUpdateDate(new Date());
            userInfo.setLastUpdateBy(BaseContext.getCurrentId());
            insert = userInfoMapper.updateByPrimaryKey(userInfo);
        }
        return insert;
    }

    @Override
    public int delete(String userId) {
        int delete = userInfoMapper.deleteByPrimaryKey(userId);
        return delete;
    }

    @Override
    public int update(UserInfo userInfo) {
        int update = userInfoMapper.updateByPrimaryKey(userInfo);
        return update;
    }

    @Override
    public UserInfo findById(String userId) {
        UserInfo userInfo = userInfoMapper.selectByPrimaryKey(userId);
        return userInfo;
    }

    @Override
    public UserInfo login(UserInfo userInfo) {
        //1先进行判断
        if (StringUtils.isEmpty(userInfo.getUserName()) || StringUtils.isEmpty(userInfo.getPassWord())) {
            throw new CustomException("请输入账号密码");
        }
        //2 根据用户名和密码查询
        //把传过来的密码进行md5加密
        String password = MD5.md5(userInfo.getPassWord());
        userInfo.setPassWord(password);
        UserInfo user = userInfoMapper.findByUNAndPW(userInfo.getUserName(), userInfo.getPassWord());
        if (user == null){
            throw new CustomException("不存在该用户，请创建");
        }
        //生成该用户对应的token，跟着user一起返回到前端
        String token = JwtTokenUtils.genToken(user.getUserId(), user.getPassWord());
        user.setToken(token);
        //对应的虚拟人物查询出来返给前端
        if(!StringUtils.isEmpty(user.getVirtuallyId())){
            VirtualCharacter virtualCharacter=virtualCharacterMapper.findById(user.getVirtuallyId());
            user.setVirtuallyName(virtualCharacter.getVirtuallyName());
            user.setVirtuallyImage(virtualCharacter.getVirtuallyImage());
            user.setPersonal(virtualCharacter.getPersonalSignature());
        }
        return user;
    }

    @Override
    public UserInfo findByById(String userId) {
        return userInfoMapper.selectByPrimaryKey(userId);
    }

    @Override
    public VirtualCharacter switchover(UserInfo userInfo) {
        userInfo.setUserId(BaseContext.getCurrentId());
        VirtualCharacter byId = virtualCharacterMapper.findById(userInfo.getVirtuallyId());
        if ("1".equals(userInfo.getStatus())){
            //status等于1的时候表示切换
            //先把之前用过的头像查询出来
            String vu =userInfoMapper.findVUById(BaseContext.getCurrentId());
            //处理数据变成list
            List<String> VIds = new ArrayList<>();
            String[] strVIds = vu.substring(1, vu.length() - 1).split(", ");
            for (String strVId : strVIds) {
                VIds.add(strVId);
            }
            VIds.add(userInfo.getVirtuallyId());
            Set<String> VIdsSet = new HashSet<>(VIds);
            //VIds转化为string存入数据库中
            String s = VIdsSet.toString();
            userInfo.setVirtuallyUsed(s);
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }else if ("2".equals(userInfo.getStatus())){
            //等于2的时候表示第一次选择
            List<String> VIds = new ArrayList<>();
            VIds.add(userInfo.getVirtuallyId());
            String s = VIds.toString();
            userInfo.setVirtuallyUsed(s);
            userInfoMapper.updateByPrimaryKeySelective(userInfo);
        }
        return byId;
    }
}
